package com.fh.controller.dictionary;

import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import com.fh.controller.logAop.MethodLog;
import com.fh.entity.system.User;
import com.fh.service.building.RecordService;
import com.fh.service.dictionary.DictionaryService;
import com.fh.util.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fh.controller.base.BaseController;
import com.fh.entity.system.Menu;
import com.fh.entity.Page;

import static com.fh.controller.system.tools.GetDatalayui.getLData;
import static com.fh.controller.system.tools.GetDatalayui.getPData;

/** 
 * 类名称：DictionaryController
 * 创建人：FH 
 * 创建时间：2017-09-28
 */
@Controller
@RequestMapping(value="/dictionary")
public class DictionaryController extends BaseController {
	
	@Resource(name="dictionaryService")
	private DictionaryService dictionaryService;
	@Resource(name = "recordService")
	private RecordService recordService;

	/**
	 * 返回json
	 */
	@RequestMapping(value = "/json")
	@ResponseBody
	public Object json(Page page) {
		PageData pd = new PageData();
		Map<String, Object> map = new HashMap<String, Object>();
		List<PageData> varList;
		String datalayui = null;

		//获取当前登录用户
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		User user = (User) session.getAttribute(Const.SESSION_USER);

		try {
			pd = this.getPageData();
			pd.put("USER_ID", user.getUSER_ID());
			getPData(page, pd);
			varList = dictionaryService.listJson(page);
			datalayui = getLData(page, varList);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			logAfter(logger);
		}
		return datalayui;
	}

	/**
	 * 获取有哪些用户的PNAME
	 */
	@RequestMapping(value = "/listPname")
	@ResponseBody
	public PageData listPname() {
		logBefore(logger, "获取有哪些用户的PNAME");
		PageData res = new PageData();
		PageData pd = this.getPageData();

		//获取当前登录用户
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		User user = (User) session.getAttribute(Const.SESSION_USER);

		try {
			pd.put("USER_ID", user.getUSER_ID());
			List<PageData> data = dictionaryService.listPname(pd);
			res.put("data", data);
			res.put("errcode", "0");
			res.put("errmsg", "ok");
		} catch (Exception e) {
			logger.error(e.toString(), e);
			res.put("data", "");
			res.put("errcode", "1");
			res.put("errmsg", e.toString());
		}

		return res;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/save")
	@ResponseBody
	public PageData save() {
		logBefore(logger, "新增Dictionary");
		PageData res = new PageData();
		PageData pd = this.getPageData();

		//获取当前登录用户
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		User user = (User) session.getAttribute(Const.SESSION_USER);

		try {
			pd.put("ID", this.get32UUID());    //主键
			pd.put("PID", 0); //PID
			pd.put("XCODE", ""); //XCODE
			pd.put("TYPE", 1); //类型
			pd.put("IS_DEL", 0); //是否删除
			pd.put("CREATE_ID", user.getUSER_ID()); //创建时间
			pd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
			dictionaryService.save(pd);
            //保存全局记录
            PageData SystemPd = new PageData();
            SystemPd.put("ID", this.get32UUID());//主键
            SystemPd.put("IS_DEL", 0); //是否删除
            SystemPd.put("SORT", 0); //排序
            SystemPd.put("CREATE_ID", user.getUSER_ID()); //创建用户
            SystemPd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
            SystemPd.put("DETAILS","新增行业配置数据");
            SystemPd.put("OPERA_TIME",new DateUtil().getTime());
            SystemPd.put("OPERATOR",user.getNAME());
            SystemPd.put("IP",user.getIP());
            SystemPd.put("OP_PD",pd.toString());
            recordService.SaveSystem(SystemPd);
			res.put("data", "");
			res.put("errcode", "0");
			res.put("errmsg", "ok");
		} catch (Exception e) {
			logger.error(e.toString(), e);
			res.put("data", "");
			res.put("errcode", "1");
			res.put("errmsg", e.toString());
		}

		return res;
	}


	/**
	 * 删除
	 */
	@RequestMapping(value="/delete")
	public void delete(PrintWriter out){
		logBefore(logger, "删除Dictionary");
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			dictionaryService.delete(pd);
			out.write("success");
			out.close();
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		
	}

	/**
	 * 通过ID获取详情信息
	 */
	@RequestMapping(value = "/info")
	@ResponseBody
	public PageData info() {
		logBefore(logger, "Dictionary详情");
		PageData res = new PageData();
		PageData pd = this.getPageData();

		try {
			PageData data = dictionaryService.findById(pd);
			res.put("data", data);
			res.put("errcode", "0");
			res.put("errmsg", "ok");
		} catch (Exception e) {
			logger.error(e.toString(), e);
			res.put("data", "");
			res.put("errcode", "1");
			res.put("errmsg", e.toString());
		}

		return res;
	}

	/**
	 * 修改
	 */
	@MethodLog(remark = "修改")
	@RequestMapping(value = "/edit")
	@ResponseBody
	public PageData edit() {
		logBefore(logger, "修改Dictionary");
		PageData res = new PageData();
		PageData pd = this.getPageData();
        //获取当前登录用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

		try {
			dictionaryService.edit(pd);
            //保存全局记录
            PageData SystemPd = new PageData();
            SystemPd.put("ID", this.get32UUID());//主键
            SystemPd.put("IS_DEL", 0); //是否删除
            SystemPd.put("SORT", 0); //排序
            SystemPd.put("CREATE_ID", user.getUSER_ID()); //创建用户
            SystemPd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
            SystemPd.put("DETAILS","修改行业配置数据");
            SystemPd.put("OPERA_TIME",new DateUtil().getTime());
            SystemPd.put("OPERATOR",user.getNAME());
            SystemPd.put("IP",user.getIP());
            SystemPd.put("OP_PD",pd.toString());
            recordService.SaveSystem(SystemPd);
            pd.put("DETAILS","修改行业配置数据");
			res.put("data", pd);
			res.put("errcode", "0");
			res.put("errmsg", "ok");
		} catch (Exception e) {
			logger.error(e.toString(), e);
			res.put("data", "");
			res.put("errcode", "1");
			res.put("errmsg", e.toString());
		}

		return res;
	}
	
	/**
	 * 列表
	 */
	@RequestMapping(value="/list")
	public ModelAndView list(Page page){
		logBefore(logger, "列表Dictionary");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			page.setPd(pd);
			List<PageData>	varList = dictionaryService.list(page);	//列出Dictionary列表
			mv.setViewName("dictionary/dictionary/dictionary_list");
			mv.addObject("varList", varList);
			mv.addObject("pd", pd);
			mv.addObject(Const.SESSION_QX,this.getHC());	//按钮权限
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
	}

	/**
	 * 通过code获取数据
	 */
	@RequestMapping(value = "/findByCode")
	@ResponseBody
	public PageData findByCode() {
		logBefore(logger, "通过code获取数据");
		PageData res = new PageData();
		PageData pd = this.getPageData();

		//获取当前登录用户
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		User user = (User) session.getAttribute(Const.SESSION_USER);

		try {
			pd.put("USER_ID", user.getUSER_ID());
			List<PageData> data = dictionaryService.findByCode(pd);
			res.put("data", data);
			res.put("errcode", "0");
			res.put("errmsg", "ok");
		} catch (Exception e) {
			logger.error(e.toString(), e);
			res.put("data", "");
			res.put("errcode", "1");
			res.put("errmsg", e.toString());
		}

		return res;
	}

	
	/**
	 * 去新增页面
	 */
	@RequestMapping(value="/goAdd")
	public ModelAndView goAdd(){
		logBefore(logger, "去新增Dictionary页面");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
			mv.setViewName("dictionary/dictionary/dictionary_edit");
			mv.addObject("msg", "save");
			mv.addObject("pd", pd);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}						
		return mv;
	}	
	
	/**
	 * 去修改页面
	 */
	@RequestMapping(value="/goEdit")
	public ModelAndView goEdit(){
		logBefore(logger, "去修改Dictionary页面");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
			pd = dictionaryService.findById(pd);	//根据ID读取
			mv.setViewName("dictionary/dictionary/dictionary_edit");
			mv.addObject("msg", "edit");
			mv.addObject("pd", pd);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}						
		return mv;
	}


	/**
	 * 新增项目类型
	 */
	@RequestMapping(value = "/savetype")
	@ResponseBody
	public PageData savetype() {
		logBefore(logger, "新增type");
		PageData res = new PageData();
		PageData pd = this.getPageData();
		//获取当前登录用户
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		User user = (User) session.getAttribute(Const.SESSION_USER);
		try {
			pd.put("ID", this.get32UUID());    //主键
			pd.put("CODE","PRO_009");
			pd.put("PID", 0);
			pd.put("XCODE", ""); //XCODE
			pd.put("TYPE", 1); //类型
			pd.put("IS_DEL", 0); //是否删除
			pd.put("CREATE_ID", user.getUSER_ID()); //创建人ID
			pd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
			pd.put("PNAME", "项目类型"); //
			dictionaryService.savetype(pd);
			//保存全局记录
			PageData SystemPd = new PageData();
			SystemPd.put("ID", this.get32UUID());//主键
			SystemPd.put("IS_DEL", 0); //是否删除
			SystemPd.put("SORT", 0); //排序
			SystemPd.put("CREATE_ID", user.getUSER_ID()); //创建用户
			SystemPd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
			SystemPd.put("DETAILS","新增项目类型");
			SystemPd.put("OPERA_TIME",new DateUtil().getTime());
			SystemPd.put("OPERATOR",user.getNAME());
			SystemPd.put("IP",user.getIP());
			SystemPd.put("OP_PD",pd.toString());
			recordService.SaveSystem(SystemPd);
			res.put("data", "");
			res.put("errcode", "0");
			res.put("errmsg", "ok");
		} catch (Exception e) {
			logger.error(e.toString(), e);
			res.put("data", "");
			res.put("errcode", "1");
			res.put("errmsg", e.toString());
		}
		return res;
	}



	/**
	 * 查询项目类型
	 *//*
	@RequestMapping(value = "/list_type")
	@ResponseBody
	public PageData type() {
		logBefore(logger, "type列表");
		PageData res = new PageData();
		PageData pd = this.getPageData();
		try {
			List<PageData> list = dictionaryService.listType(pd);
			System.out.println(list);
			System.out.println(list);
			res.put("data", list);
			res.put("errcode", "0");
			res.put("errmsg", "ok");
		} catch (Exception e) {
			logger.error(e.toString(), e);
			res.put("data", "");
			res.put("errcode", "1");
			res.put("errmsg", e.toString());
		}
		return res;
	}
*/

	/**
	 * 修改项目类型
	 */
	@RequestMapping(value = "/edittype")
	@ResponseBody
	public PageData edittype() {
		logBefore(logger, "修改room");
		PageData res = new PageData();
		PageData pd = this.getPageData();
		try {
			dictionaryService.edittype(pd);
			//获取当前登录用户
			Subject currentUser = SecurityUtils.getSubject();
			Session session = currentUser.getSession();
			User user = (User) session.getAttribute(Const.SESSION_USER);
			//保存全局记录
			PageData SystemPd = new PageData();
			SystemPd.put("ID", this.get32UUID());//主键
			SystemPd.put("IS_DEL", 0); //是否删除
			SystemPd.put("SORT", 0); //排序
			SystemPd.put("CREATE_ID", user.getUSER_ID()); //创建用户
			SystemPd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
			SystemPd.put("DETAILS","修改项目类型");
			SystemPd.put("OPERA_TIME",new DateUtil().getTime());
			SystemPd.put("OPERATOR",user.getNAME());
			SystemPd.put("IP",user.getIP());
			SystemPd.put("OP_PD",pd.toString());
			recordService.SaveSystem(SystemPd);
			res.put("data", "");
			res.put("errcode", "0");
			res.put("errmsg", "ok");
		} catch (Exception e) {
			logger.error(e.toString(), e);
			res.put("data", "");
			res.put("errcode", "1");
			res.put("errmsg", e.toString());
		}

		return res;
	}


	/**
	 * 删除项目类型
	 */
	@RequestMapping(value="/deletetype")
	public PageData deletetype(PrintWriter out){
		logBefore(logger, "删除项目类型");
		PageData res = new PageData();
		PageData pd = this.getPageData();
		try{
			pd = this.getPageData();
			dictionaryService.deletetype(pd);
			//获取当前登录用户
			Subject currentUser = SecurityUtils.getSubject();
			Session session = currentUser.getSession();
			User user = (User) session.getAttribute(Const.SESSION_USER);
			//保存全局记录
			PageData SystemPd = new PageData();
			SystemPd.put("ID", this.get32UUID());//主键
			SystemPd.put("IS_DEL", 0); //是否删除
			SystemPd.put("SORT", 0); //排序
			SystemPd.put("CREATE_ID", user.getUSER_ID()); //创建用户
			SystemPd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
			SystemPd.put("DETAILS","删除项目类型");
			SystemPd.put("OPERA_TIME",new DateUtil().getTime());
			SystemPd.put("OPERATOR",user.getNAME());
			SystemPd.put("IP",user.getIP());
			SystemPd.put("OP_PD",pd.toString());
			recordService.SaveSystem(SystemPd);
			res.put("data", "");
			res.put("errcode", "0");
			res.put("errmsg", "ok");
		} catch (Exception e) {
			logger.error(e.toString(), e);
			res.put("data", "");
			res.put("errcode", "1");
			res.put("errmsg", e.toString());
		}
		return res;
	}


	/**
	 * 通过ID获取字典项目类型中的详情信息
	 */
	@RequestMapping(value = "/infotype")
	@ResponseBody
	public PageData infotype() {
		logBefore(logger, "字典表中项目类型详情");
		PageData res = new PageData();
		PageData pd = this.getPageData();
		try {
			PageData data = dictionaryService.findTypeById(pd);
			//获取根据房间单元 因为单元暂时固定 取房间首位 不取数据库
			res.put("data", data);
			res.put("errcode", "0");
			res.put("errmsg", "ok");
		} catch (Exception e) {
			logger.error(e.toString(), e);
			res.put("data", "");
			res.put("errcode", "1");
			res.put("errmsg", e.toString());
		}

		return res;
	}


	/**
	 * 返回字典表中项目类型list 列表
	 */
	@RequestMapping(value = "/jsontype")
	@ResponseBody
	public Object typejson(Page page) {
		PageData pd = new PageData();
		Map<String, Object> map = new HashMap<String, Object>();
		List<PageData> varList;
		String datalayui = null;

		//获取当前登录用户
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		User user = (User) session.getAttribute(Const.SESSION_USER);

		try {
			//测试分页 导出为layui的json数据
			pd = this.getPageData();
			pd.put("USER_ID", user.getUSER_ID());
			getPData(page, pd);//必填 2参
			//List<PageData> list = roomService.listType(pd);
			varList = dictionaryService.listtype(page);    //列出Building列表
			datalayui = getLData(page, varList);//必填 3参
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			logAfter(logger);
		}
		return datalayui;
	}





	
	/**
	 * 批量删除
	 */
	@RequestMapping(value="/deleteAll")
	@ResponseBody
	public Object deleteAll() {
		logBefore(logger, "批量删除Dictionary");
		PageData pd = new PageData();		
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			pd = this.getPageData();
			List<PageData> pdList = new ArrayList<PageData>();
			String DATA_IDS = pd.getString("DATA_IDS");
			if(null != DATA_IDS && !"".equals(DATA_IDS)){
				String ArrayDATA_IDS[] = DATA_IDS.split(",");
				dictionaryService.deleteAll(ArrayDATA_IDS);
				pd.put("msg", "ok");
			}else{
				pd.put("msg", "no");
			}
			pdList.add(pd);
			map.put("list", pdList);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			logAfter(logger);
		}
		return AppUtil.returnObject(pd, map);
	}
	
	/*
	 * 导出到excel
	 * @return
	 */
	@RequestMapping(value="/excel")
	public ModelAndView exportExcel(){
		logBefore(logger, "导出Dictionary到excel");
		ModelAndView mv = new ModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try{
			Map<String,Object> dataMap = new HashMap<String,Object>();
			List<String> titles = new ArrayList<String>();
			titles.add("CODE");	//1
			titles.add("PID");	//2
			titles.add("NAME");	//3
			titles.add("PNAME");	//4
			titles.add("XCODE");	//5
			titles.add("SORT");	//6
			titles.add("CREATE_ID");	//7
			titles.add("CREATE_DATE");	//8
			titles.add("IS_DEL");	//9
			dataMap.put("titles", titles);
			List<PageData> varOList = dictionaryService.listAll(pd);
			List<PageData> varList = new ArrayList<PageData>();
			for(int i=0;i<varOList.size();i++){
				PageData vpd = new PageData();
				vpd.put("var1", varOList.get(i).getString("CODE"));	//1
				vpd.put("var2", varOList.get(i).getString("PID"));	//2
				vpd.put("var3", varOList.get(i).getString("NAME"));	//3
				vpd.put("var4", varOList.get(i).getString("PNAME"));	//4
				vpd.put("var5", varOList.get(i).getString("XCODE"));	//5
				vpd.put("var6", varOList.get(i).getString("SORT"));	//6
				vpd.put("var7", varOList.get(i).getString("CREATE_ID"));	//7
				vpd.put("var8", varOList.get(i).getString("CREATE_DATE"));	//8
				vpd.put("var9", varOList.get(i).getString("IS_DEL"));	//9
				varList.add(vpd);
			}
			dataMap.put("varList", varList);
			ObjectExcelView erv = new ObjectExcelView();
			mv = new ModelAndView(erv,dataMap);
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
	}
	
	/* ===============================权限================================== */
	public Map<String, String> getHC(){
		Subject currentUser = SecurityUtils.getSubject();  //shiro管理的session
		Session session = currentUser.getSession();
		return (Map<String, String>)session.getAttribute(Const.SESSION_QX);
	}
	/* ===============================权限================================== */
	
	@InitBinder
	public void initBinder(WebDataBinder binder){
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(format,true));
	}

	/**
	 * 增加通用行业
	 */
	@RequestMapping(value = "/demo")
	@ResponseBody
	public PageData demo() {
		logBefore(logger, "通过code获取数据");
		PageData res = new PageData();
		PageData pd = this.getPageData();

		//获取当前登录用户
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		User user = (User) session.getAttribute(Const.SESSION_USER);

		try {
			pd.put("USER_ID", user.getUSER_ID());
			String S1="险业、采矿、能源、餐饮、宾馆、电讯业、房地产、服务、服装业、公益组织、广告业、航空航天、化学、健康、保健、建筑业、教育、培训、计算机、金属冶炼、消防、会计、美容、媒体、出版、木材、造纸、零售、批发、农业、旅游业、司法、体育运动、学术研究、演艺、医疗服务、艺术、设计、银行、金融、因特网、音乐舞蹈、邮政快递、运输业、政府机关、机械制造、咨询、修理维修";
			String S2=S1.replace("、",",");
			String[] S3=S2.split(",");
			int id=100;
			int ids=0;
			for(String s3:S3){
				id++;
				ids++;
				pd.put("ID", id);    //主键
				System.out.println(id);
				pd.put("PID", 0); //PID
				pd.put("CODE", "PRO_007"); //PID
				pd.put("XCODE", ""); //XCODE
				pd.put("TYPE", 1); //类型
				pd.put("SORT", ids); //类型
				pd.put("IS_DEL", 0); //是否删除
				pd.put("PNAME", "所属行业"); //是否删除
				pd.put("NAME", s3); //是否删除
				pd.put("CREATE_ID", ""); //创建时间
				pd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
				dictionaryService.save(pd);
			}
//			System.out.println(S2);
			res.put("errcode", "0");
			res.put("errmsg", "ok");
		} catch (Exception e) {
			logger.error(e.toString(), e);
			res.put("data", "");
			res.put("errcode", "1");
			res.put("errmsg", e.toString());
		}

		return res;
	}
}
